package com.demo.java.spring.tx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CatalogServiceImpl implements CatalogService {

    @Autowired
    private CatalogDao catalogDao;

    @Transactional
    public Catalog findById(int id) {
        return catalogDao.findById(id);
    }

    @Transactional
    public Catalog findByIdForUpdateSql(int id) {
        return catalogDao.findByIdForUpdateSql(id);
    }

    @Transactional
    public Catalog updateCatalog(Catalog catalog) {
        catalogDao.update(catalog);
        return catalog;
    }

    @Override
    @Transactional
    public Catalog updateCatalogExclusive() {
        // 悲观锁解决并发事务问题，select ... for update必须和update在同一个事务中
        Catalog catalog = catalogDao.findByIdForUpdateSql(1);
        catalog.setBrowseCount(catalog.getBrowseCount()+1);
        catalogDao.update(catalog);
        return catalog;
    }
}
